/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { useContext, useState, useRef, useEffect } from 'react';
import { View, Text, ScrollView, TouchableOpacity, Dimensions, StyleSheet, Image, NativeSyntheticEvent, ScrollEvent } from 'react-native';
import type { ViewStyle } from 'react-native';
import { useBreakpointValue, useHeightBreakpointValue } from '@hadss/react_native_adaptive_layout';
import useDebounce from '../../hooks/useDebounce';
import Context from '../../Context';

const MODELIST = ['大光圈', '夜景', '人像', '拍照', '录像', '专业', '更多'];
const DOT = require('../../../../../assets/pic/reddot.png');

/**
 * @description 滑动设置相机模式
 * @returns 
 */
const ModeSetting = () : JSX.Element => {
  const { isOpenVideo, setIsOpenVideo, isOpenPhoto, setIsOpenPhoto } = useContext(Context);
  const width = Dimensions.get('window').width;
  const ref = useRef<ScrollView>(null);
  const { setMode, isRecording } = useContext(Context);
  const [selectedIndex, setSelectedIndex] = useState(0);

  const isSmall = useHeightBreakpointValue<boolean>({
    base: false,
    sm: true,
    md: true,
    lg: false
  });

  /** 默认选中初始化，根据屏幕类型设置x | y */
  const handleSelected = useBreakpointValue<(index: number) => void>({
    base: (index) => ref?.current?.scrollTo?.({ x: itemSize * index, animated: false })
  });

  useEffect(() : void => {
    handleSelected?.(3);
  }, []);

  const handleModeSetting = (index: number) : void => {
    setSelectedIndex(index);
    setIsOpenPhoto(index === 3);
    setIsOpenVideo(index === 4);
    setMode(index === 4 ? 'video' : 'photo');
  };
  const debouncedSetting = useDebounce(handleModeSetting, 30);

  const handleScroll = (e: NativeSyntheticEvent<ScrollEvent>): void => {
    const offsetX = e.nativeEvent.contentOffset.x;
    const index = Math.round(offsetX / itemSize);
    if (index >= 0 && index < MODELIST.length && index !== selectedIndex) {
      debouncedSetting(index);
    }
  };
  const handlePress = (index: number): void => {
    if (index === selectedIndex) {
      return;
    }
    handleSelected?.(index);
  };

  /** horizontal模式下是item宽度 非horizontal模式下是item高度 需要把两边间距也算上 各取一半 */
  const itemSize = useBreakpointValue<number>({
    base: 56
  }) as number;

  const containerStyle = useBreakpointValue<ViewStyle>({
    base: isSmall ? {
      height: 32,
      marginBottom: 24,
      width: 144,
      marginLeft: (width - 144) / 2,
      opacity: isRecording ? 0 : 1
    } : {
      height: 32,
      marginBottom: 24,
      marginTop: 32,
      opacity: isRecording ? 0 : 1
    }
  });

  const contentContainer = useBreakpointValue<ViewStyle>({
    base: isSmall ? {
      paddingHorizontal: (144 - itemSize) / 2
    } : {
      // 这里设置是为了能够让第一个和最后一个能够滑动显示
      paddingHorizontal: (width - itemSize) / 2
    }
  });
  /** 不同屏幕类型注意适配 */
  const itemStyle = useBreakpointValue<ViewStyle>({
    base: {
      alignItems: 'center',
      justifyContent: 'center',
      width: itemSize,
      height: 20,
    }
  });
  /** 是否水平根据端点值设置 */
  const horizontal = useBreakpointValue<boolean>({
    base: true
  });
  /** 指示器容器样式 */
  const indicator = useBreakpointValue<ViewStyle>({
    base: isSmall ? {
      height: 6,
      width: 6,
      position: 'absolute',
      bottom: 0,
      left: (144 - 6) / 2
    } : {
      height: 6,
      width: 6,
      position: 'absolute',
      bottom: 0,
      left: (width - 6) / 2
    }
  });
  return (
    <View style={containerStyle}>
      <ScrollView
        ref={ref}
        horizontal={horizontal}
        showsHorizontalScrollIndicator={false}
        snapToInterval={itemSize}
        decelerationRate={'fast'}
        scrollEventThrottle={16}
        onScroll={handleScroll}
        contentContainerStyle={contentContainer}
        disableIntervalMomentum
      >
        {
          MODELIST.map((item, index) : JSX.Element => (
            <TouchableOpacity style={itemStyle} key={item} onPress={(): void => handlePress(index)}>
              <Text style={{ ...styles.text, fontWeight: index === selectedIndex ? '600' : '400' }}>{item}</Text>
            </TouchableOpacity>
          ))
        }
      </ScrollView>
      <View style={indicator}>
        <Image source={DOT} style={{ width: 6, height: 6 }} />
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  text: {
    color: 'rgba(255, 255, 255, 1)',
    fontSize: 14,
    lineHeight: 20
  }
});

export default ModeSetting;
